﻿using System.Collections.Generic;
using UnityEngine;

namespace SSAAD {
	// Note to self: AvailablePart for editor stuff.
    public class JMPScienceModule : PartModule {
		[KSPField]
		public bool scienceOn;

		[KSPField(guiActive = true)]
		public float electricCost;

		[KSPField(guiActive = true)]
		public float dataRate;

		[KSPField]
		public string experimentID;

		public void FixedUpdate() {
			if (part.isControllable && scienceOn) {
				float powerCost = electricCost * TimeWarp.CurrentRate;
				float power = part.RequestResource("ElectricCharge", powerCost);
				float ratio = 1;
				if (electricCost > 0) { ratio = power / powerCost; }
				float dataGenerated = ratio * dataRate * TimeWarp.CurrentRate;

				if (dataGenerated > 0) {
					ScienceExperiment exp = ResearchAndDevelopment.GetExperiment(experimentID);
					ExperimentSituations sit = ScienceUtil.GetExperimentSituation(vessel);

					if (exp.IsAvailableWhile(sit, vessel.mainBody)) {
						string biome = "";

						if (exp.BiomeIsRelevantWhile(sit)) {
							biome = Vessel.GetLandedAtString(vessel.landedAt);
							if (biome == string.Empty) { biome = ScienceUtil.GetExperimentBiome(vessel.mainBody, vessel.latitude, vessel.longitude); }
						}

						ScienceSubject sub = ResearchAndDevelopment.GetExperimentSubject(exp, sit, vessel.mainBody, biome);

						foreach (JMPScienceStorageModule s in part.FindModulesImplementing<JMPScienceStorageModule>()) {
							dataGenerated = s.handleData(dataGenerated, sub);
							if (dataGenerated <= 0) { break; }
						}

						if (dataGenerated > 0) {
							foreach (JMPScienceStorageModule s in vessel.FindPartModulesImplementing<JMPScienceStorageModule>()) {
								dataGenerated = s.handleData(dataGenerated, sub);
								if (dataGenerated <= 0) { break; }
							}
						}
					}
				}
			}
		}

		[KSPEvent(guiActive = true, guiName = "Activate")]
		public void Activate() {
			Events["Deactivate"].active = true;
			Events["Activate"].active = false;
			scienceOn = true;
		}

		[KSPEvent(guiActive = true, guiName = "Deactivate")]
		public void Deactivate() {
			Events["Deactivate"].active = false;
			Events["Activate"].active = true;
			scienceOn = false;
		}

		public override void OnLoad(ConfigNode node) {
			if (scienceOn) { Activate(); }
			else { Deactivate(); }
		}
    }
}
